package com.hugehard.here;

import java.util.ArrayList;
import java.util.Locale;

import android.app.AlertDialog;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.provider.ContactsContract;
import android.telephony.SmsManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.hugehard.here.ContactsManager.BaseContactItem;
import com.pinyin4android.PinyinUtil;

public class SearchResultsView {
	private final static String TAG = SearchResultsView.class.getSimpleName();
	
	private final Context mContext;
	private final View mView;
	private final SearchResultAdapter mAdapter;
	private final ArrayList<BaseContactItem> mContactItemList;
	private final LayoutInflater mInflater;
	
	public View getView() {
		return mView;
	}
	
	public SearchResultsView(Context context, ArrayList<BaseContactItem> contactItemList) {
		mContext = context;
		mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		
		ListView searchResultListView = new ListView(context);
		mView = searchResultListView;
		mContactItemList = contactItemList;
		
		mAdapter = new SearchResultAdapter();
		searchResultListView.setAdapter(mAdapter);
		
		searchResultListView.setOnItemClickListener(mOnItemClickListener);
	}
	
	private OnItemClickListener mOnItemClickListener = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			LayoutInflater inflater = (LayoutInflater)
			        mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View dialogView = inflater.inflate(R.layout.hh_dialog,
			        null);

			TextView text = (TextView) dialogView.findViewById(R.id.hh_dialog_textview);
			String contentStr = mContext.getResources().getString(R.string.hh_dialog_content);
			final BaseContactItem item = mAdapter.getItem(arg2);
			
			if (item != null) {
				text.setText(contentStr + " " + item.mContactName);
				AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
				builder.setView(dialogView);
				final AlertDialog alertDialog = builder.create();
				
				View cancelBtn = dialogView.findViewById(R.id.btn_cancel);
				cancelBtn.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						alertDialog.cancel();
					}
				});
				
				View okBtn = dialogView.findViewById(R.id.btn_ok);
				okBtn.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {						
						LocationManager locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
						Criteria crit = new Criteria();
						crit.setAccuracy(Criteria.ACCURACY_FINE);
						String provider = locationManager.getBestProvider(crit, true);
						Location location = locationManager.getLastKnownLocation(provider);
						double latitude = location.getLatitude();
						double longtiude = location.getLongitude();
						String smsText = String.format(Locale.getDefault(), "I'm here! (%f, %f)", latitude, longtiude);
						
						try {
							SmsManager smsManager = SmsManager.getDefault();
							smsManager.sendTextMessage(item.mPhoneNumber, null,
									smsText, null, null);
							Toast.makeText(mContext, "SMS Sent!",
									Toast.LENGTH_LONG).show();
						} catch (Exception e) {
							Toast.makeText(mContext,
									"SMS faild, please try again later!",
									Toast.LENGTH_LONG).show();
							e.printStackTrace();
						}
						alertDialog.cancel();
					}
				});
				
				alertDialog.show();
			}
		}
	};
	
	public void onSearchKeyWordChanged(String searchKeyWord) {
		ArrayList<BaseContactItem> searchResultItemList = new ArrayList<BaseContactItem>();
		if (searchKeyWord != null && searchKeyWord.isEmpty() == false) {
			searchKeyWord = searchKeyWord.toLowerCase(Locale.getDefault());
			for (int i = 0; i < mContactItemList.size(); i++) {
				BaseContactItem item = mContactItemList.get(i);
				if (item != null) {
					String name = item.mContactName.toLowerCase(Locale.getDefault());
					String num = item.mPhoneNumber.toLowerCase(Locale.getDefault());
					if (item.mPinyin == null || item.mPinyin.isEmpty()) {
						item.mPinyin = PinyinUtil.toPinyin(mContext, name);
						item.mPinyin = item.mPinyin.toLowerCase(Locale.getDefault());
					}
					if (name.contains(searchKeyWord)
							|| num.contains(searchKeyWord)
							|| item.mPinyin.contains(searchKeyWord)) {
						searchResultItemList.add(item);
					}
				}
			}
		}
		mAdapter.setItems(searchResultItemList);
		mAdapter.notifyDataSetChanged();
	}
	
	private class SearchResultAdapter extends BaseAdapter {
		private ArrayList<BaseContactItem> mItems = null;
		
		private class ViewHolder {
			public TextView mContactNameTv = null;
			public ImageView mPhoneTypeIv = null;
		}
		
		public void setItems(ArrayList<BaseContactItem> items) {
			mItems = items;
		}

		@Override
		public int getCount() {
			int count = mItems != null ? mItems.size() : 0;
			return count;
		}

		@Override
		public BaseContactItem getItem(int position) {
			BaseContactItem retItem = null;
			if (mItems != null && position >= 0 && position < mItems.size()) {
				retItem = mItems.get(position);
			}
			return retItem;
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder = null;
			if (convertView == null) {
				convertView = mInflater.inflate(R.layout.contact_item, parent, false);
				viewHolder = new ViewHolder();
				viewHolder.mContactNameTv = (TextView) convertView.findViewById(R.id.contact_name_textview);
				viewHolder.mPhoneTypeIv = (ImageView) convertView.findViewById(R.id.contact_phone_type_imageview);
				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			BaseContactItem item = getItem(position);
			if (item != null) {
				viewHolder.mContactNameTv.setText(item.mContactName);
				if (item.mType == ContactsContract.CommonDataKinds.Phone.TYPE_HOME) {
					viewHolder.mPhoneTypeIv.setImageResource(R.drawable.phone_type_home);
					viewHolder.mPhoneTypeIv.setVisibility(View.VISIBLE);
				} else if (item.mType == ContactsContract.CommonDataKinds.Phone.TYPE_WORK) {
					viewHolder.mPhoneTypeIv.setImageResource(R.drawable.phone_type_work);
					viewHolder.mPhoneTypeIv.setVisibility(View.VISIBLE);
				} else {
					viewHolder.mPhoneTypeIv.setVisibility(View.GONE);
				}
			}
			return convertView;
		}
	}
}